package com.tfxy.hxl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tfxy.hxl.R;
import com.tfxy.hxl.entity.UserPreference;
import com.tfxy.hxl.mapper.UserPreferenceMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户偏好控制器（精简版）
 */
@RestController
@RequestMapping("/user-preference")
@Tag(name = "用户偏好管理", description = "用户偏好核心功能")
public class UserPreferenceController {

    @Autowired
    private UserPreferenceMapper userPreferenceMapper;

    /**
     * 1. 获取用户偏好
     */
    @GetMapping("/user/{userId}")
    @Operation(summary = "获取用户偏好")
    public R getUserPreferences(@Parameter(description = "用户ID") @PathVariable Long userId) {
        QueryWrapper<UserPreference> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .eq("deleted", 0)
                   .orderByDesc("preference_score");
        
        List<UserPreference> preferences = userPreferenceMapper.selectList(queryWrapper);
        return R.ok().data("preferences", preferences);
    }

    /**
     * 2. 更新偏好
     */
    @PutMapping("/update")
    @Operation(summary = "更新偏好")
    public R updatePreference(@RequestBody UserPreference preference) {
        if (preference.getId() == null) {
            return R.error().message("偏好ID不能为空");
        }
        
        preference.setUpdateTime(new Date());
        
        int result = userPreferenceMapper.updateById(preference);
        if (result > 0) {
            return R.ok().message("偏好更新成功");
        } else {
            return R.error().message("偏好更新失败");
        }
    }

    /**
     * 3. 分析偏好数据
     */
    @GetMapping("/analyze/{userId}")
    @Operation(summary = "分析偏好数据")
    public R analyzeUserPreferences(@Parameter(description = "用户ID") @PathVariable Long userId) {
        QueryWrapper<UserPreference> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .eq("deleted", 0);
        
        List<UserPreference> preferences = userPreferenceMapper.selectList(queryWrapper);
        
        Map<String, Object> analysis = new HashMap<>();
        analysis.put("totalCategories", preferences.size());
        
        if (!preferences.isEmpty()) {
            // 计算平均分数
            double averageScore = preferences.stream()
                    .mapToDouble(p -> p.getPreferenceScore().doubleValue())
                    .average().orElse(0.0);
            analysis.put("averageScore", averageScore);
            
            // 找到最高偏好分类
            UserPreference topPreference = preferences.stream()
                    .max((p1, p2) -> p1.getPreferenceScore().compareTo(p2.getPreferenceScore()))
                    .orElse(null);
            
            if (topPreference != null) {
                analysis.put("topCategoryId", topPreference.getCategoryId());
                analysis.put("topScore", topPreference.getPreferenceScore());
            }
        } else {
            analysis.put("averageScore", 0.0);
            analysis.put("topCategoryId", null);
            analysis.put("topScore", null);
        }
        
        return R.ok().data("analysis", analysis);
    }
}
